/*
 * Copyright 2010 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.google.websocket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;
import java.util.Set;

/**
 * Base class for HTTP-compatible WebSocket handshake implementations.  The
 * distinguishing feature here is that an HTTP request line and headers can be
 * read externally, which can then be used to choose a handshake implementation.
 */
public abstract class HttpCompatibleHandshake extends WebSocketHandshakeBase {

  /**
   * Check to see if the HTTP request is for this handshake.
   * 
   * @param requestLine
   * @param headers
   * @return true if these headers could be valid for this handshake.
   */
  public abstract boolean matches(String requestLine,
      Map<String, String> headers);

  public WebSocket serverHandshake(
      InputStream in, OutputStream out, Set<Extension> extensions, int port)
      throws IOException {
    String line = Util.readUtf8Line(in);
    Map<String, String> headerFields = Util.readHeaderFields(in);
    if (!matches(line, headerFields)) {
      throw new IOException("Unexpected HTTP headers: line=" + line
          + ", headers=" + headerFields);
    }
    return serverHandshake(line, headerFields, in, out, extensions, port);
  }

  /**
   * Given a request line and the HTTP headers already read, perform the
   * WebSocket handshake.
   * 
   * @param requestLine
   * @param headers
   * @param in
   * @param out
   * @param extensions
   * @param port
   * @return a WebSocket instance for an established connection
   * @throws IOException if the connection cannot be established
   */
  public abstract WebSocket serverHandshake(String requestLine,
      Map<String, String> headers, InputStream in, OutputStream out,
      Set<Extension> extensions, int port) throws IOException;
}